package com.microframework.base.core.util.sql;

import com.jfinal.plugin.activerecord.DbKit;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SqlFieldFetcher {
    
    /**
     * 获取 SQL 查询结果的字段信息
     * @param sql SQL 语句
     * @param params SQL 参数
     * @return 字段信息列表
     */
    public static List<String> getQueryFields(String sql, Object... params) {
        List<String> fields = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        
        try {
            // 获取数据库连接
            conn = DbKit.getConfig("mine").getConnection();
            // 创建预处理语句
            pst = conn.prepareStatement(sql);
            
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i + 1, params[i]);
            }
            
            // 执行查询
            rs = pst.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            
            // 获取字段数量
            int columnCount = metaData.getColumnCount();
            
            // 遍历所有字段
            for (int i = 1; i <= columnCount; i++) {
                // 获取字段名（使用别名优先）
                String columnName = metaData.getColumnLabel(i);
                fields.add(columnName);
                
                // 可选：获取其他字段信息
                // String columnType = metaData.getColumnTypeName(i);
                // int columnSize = metaData.getPrecision(i);
                // boolean isNullable = metaData.isNullable(i) == ResultSetMetaData.columnNullable;
                // System.out.println(columnName + " | " + columnType + " | " + columnSize);
            }
        } catch (SQLException e) {
            throw new RuntimeException("获取字段信息失败", e);
        } finally {
            // 关闭资源
        	DbKit.getConfig().close(conn);
        }
        return fields;
    }

    public static void main(String[] args) {
        // 示例用法
        String sql = "SELECT id AS userId, name, age FROM user WHERE age > ?";
        List<String> fields = getQueryFields(sql, 18);
        
        System.out.println("查询包含字段:");
        fields.forEach(System.out::println);
        // 输出: userId, name, age
    }
}
